<template>
  <div class="home">
    <div id="main" ref="one" style="width: 1000px;height:500px;"></div>
  </div>
</template>

<script>

import { inject,reactive,onMounted,getCurrentInstance } from 'vue'

export default {
  name: "One",
  setup(){

    let $echarts = inject("echarts");
    let $http = inject("axios");
    let {proxy} = getCurrentInstance()

    let testData = reactive([])
    let xData = reactive([])
    let yData = reactive([])

    function setData() {
      xData = testData.map(v => v.nationname)
      yData = testData.map(v => v.totalconsumption)
    }

    onMounted(()=>{
      getData()
    })

    function initChart() {
      let chart = $echarts.init(proxy.$refs.one);
      // 把配置和数据放这里
      chart.setOption({
        title: {
          text: '1997年12月消费额最高的5个国家'
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value',
          scale:true
        },
        series: [
          {
            data: yData,
            type: 'bar'
          }
        ]
      });
    }

    let getData = function () {
      $http({
        url:"http://101.43.144.48:6789/api/data",
        method:"post",
        data:{
          "start":199712,
          "end":199712
        }
      }).then((res) => {
        testData = res.data
        filter()
        setData()
        initChart()
        console.log(testData)
        console.log(xData)
        console.log(yData)
      })
    }

    let filter = function () {
      testData.sort((a ,b) => {
        return b.totalconsumption - a.totalconsumption
      })
      testData = testData.slice(0, 5)
    }
  }
}
</script>
